package cn.wolfcode.mq;

import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(consumerGroup = "OrderPeddingGroup",topic = MQConstant.ORDER_PEDDING_TOPIC)
public class OrderPeddingQueueListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage orderMessage) {
        OrderMQResult result = new OrderMQResult();
        result.setToken(orderMessage.getToken());//token信息，用户WebSocket通知客户端
        try {
            SeckillProductVo vo = seckillProductService.find(orderMessage.getTime(), orderMessage.getSeckillId());
//            int i = 1/0;
            //给用户创建秒杀订单，并执行库存-1操作
            String orderNo = orderInfoService.doSeckill(vo, orderMessage.getUserPhone().toString());
            result.setOrderNo(orderNo);
            result.setSeckillId(orderMessage.getSeckillId());
            result.setTime(orderMessage.getTime());
            //秒杀成功，发送延时消息
            Message<OrderMQResult> msg = MessageBuilder.withPayload(result).build();
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,msg,3000,MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            result.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            //如果一个用户同时进来两个线程，有一个肯定是秒杀不了订单的，直接报错回滚了数据，
            // 所以，Redis中预库存-1了，数据库中却没有减一，这样会使我们少卖一个商品
            //同步Redis中的预库存信息
            seckillProductService.syncStorckCountToRedis(orderMessage.getTime(),orderMessage.getSeckillId());
        }
        //无论成功和失败都将信息放入MQ信息队列中,topic = ORDER_RESULT_TOPIC
        rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC,result);
    }
}